package com.github.pires.obd.paizhao.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 项目名称：图片处理
 * 创建人：mwb
 * 创建时间：2018/11/11 21:52
 */
public class PhotoBitmapUtils {
    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

//    // 压缩图片，处理某些手机拍照角度旋转的问题
//    public static Bitmap compressImage(Activity context, String filePath, String name)
//            throws FileNotFoundException {
//        Bitmap bm = getSmallBitmap(context, filePath);
//        bm = compress(bm);
//        int degree = readPictureDegree(filePath);
//        if (degree != 0) {// 旋转照片角度
//            bm = rotateBitmap(bm, degree);
//        }
//        String path = name;
//        // Log.i("mwb", "path:" + path);
//        File outputFile = new File(path);
//        FileOutputStream out = new FileOutputStream(outputFile);
//        bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
//        return bm;
//    }
//
//    // 根据路径获得图片并压缩，返回bitmap用于显示
//    public static Bitmap getSmallBitmap(Activity context, String filePath) {
//        final BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(filePath, options);
//
//        DisplayMetrics dm = new DisplayMetrics();
//        // 获取屏幕信息
//        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
//        int screenHeigh = dm.heightPixels;
//
//        options.inSampleSize = calculateInSampleSize(options, screenWidth,
//                screenHeigh);
//        options.inJustDecodeBounds = false;
//
//        return BitmapFactory.decodeFile(filePath, options);
//    }

    // 判断图片的角度
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    degree = 0;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        LogUtil.i("degree:" + degree);
        return degree;
    }

    // 旋转图片
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    // 对图片质量进压缩
    public static Bitmap compress(Bitmap bm) {
        if (bm == null) {
            LogUtil.e("PhoteBitmapUtils compress bitmap == null");
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 20, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

        int qulity = 20;
        while (baos.toByteArray().length / 1024 > 40) {
            baos.reset();// 重置baos即清空baos
            bm.compress(Bitmap.CompressFormat.JPEG, qulity, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            qulity -= 100;// 每次都减少100
            if (qulity <= 0) {
                break;
            }
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        bm = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片


//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bm.compress(Bitmap.CompressFormat.JPEG, 20, baos);
//        byte[] bytes = baos.toByteArray();
//        bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//        LogUtil.i("压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)
//                + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight()
//                + "bytes.length= " + (bytes.length / 1024) + "KB"
//                + "quality=" + 20);
        return bm;
    }

    /**
     * 把原图按1/10的比例压缩
     *
     * @param path 原图的路径
     * @return 压缩后的图片
     */
    public static Bitmap getCompressPhoto(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 10; // 图片的大小设置为原来的十分之一
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        options = null;
        return bmp;
    }

    /**
     * 文件转bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapFromFilePath(String filePath) {
        if (filePath == null) {
            LogUtil.i("filePath == null");
            return null;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        return bitmap;
    }

    /**
     * bitmap转jpg
     *
     * @param bitmap
     * @param name
     */
    public static File bitmap2JPEG(Context context, Bitmap bitmap, String name) {
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/pic/" + name);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
//            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
                out.close();
            } else {
                LogUtil.i("转化失败");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


//        ByteArrayOutputStream baos = null;
//        try {
//            if (bitmap != null) {
//                baos = new ByteArrayOutputStream();
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos); // 压缩比例
//
//                baos.flush();
//                baos.close();
//
//                byte[] bitmapBytes = baos.toByteArray();
//                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
////                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (baos != null) {
//                    baos.flush();
//                    baos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        return file;
    }

}


